package com.mall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mall.common.constant.ProductConstant;
import com.mall.common.page.PageData;
import com.mall.common.service.impl.CrudServiceImpl;
import com.mall.common.utils.ConvertUtils;
import com.mall.product.dao.AttrDao;
import com.mall.product.dto.AttrAttrgroupRelationDTO;
import com.mall.product.dto.AttrDTO;
import com.mall.product.entity.AttrAttrgroupRelationEntity;
import com.mall.product.entity.AttrEntity;
import com.mall.product.entity.AttrGroupEntity;
import com.mall.product.entity.ProductAttrValueEntity;
import com.mall.product.service.AttrAttrgroupRelationService;
import com.mall.product.service.AttrGroupService;
import com.mall.product.service.AttrService;
import com.mall.product.service.CategoryService;
import com.mall.product.vo.AttrGroupRelationVo;
import com.mall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品属性
 *
 * @author xjc xjc@163.com
 * @since 1.0.0 2022-07-17
 */
@Service
public class AttrServiceImpl extends CrudServiceImpl<AttrDao, AttrEntity, AttrDTO> implements AttrService {

    @Resource
    private AttrAttrgroupRelationService relationService;
    @Resource
    private AttrGroupService attrGroupService;
    @Resource
    private CategoryService categoryService;

    @Override
    public QueryWrapper<AttrEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Transactional
    @Override
    public void saveAttrDto(AttrDTO dto) {
        // 保存基础数据
        save(dto);
        // 销售属性不需要保存类型 ,并且不能为空
        if (dto.getAttrType() != ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType()&& dto.getAttrGroupId()!=null) {
            // 保存关联关系
            AttrAttrgroupRelationDTO attrAttrgroupRelationDTO = new AttrAttrgroupRelationDTO();
            attrAttrgroupRelationDTO.setAttrId(dto.getAttrId());
            attrAttrgroupRelationDTO.setAttrGroupId(dto.getAttrGroupId());
            relationService.save(attrAttrgroupRelationDTO);
        }
    }

    @Override
    public PageData<AttrVo> pageByParam(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        String type = (String) params.get("type");
        if (type != null) {
            if (type.equals(String.valueOf(ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType()))) {
                queryWrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType());
            } else
                queryWrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType());
        }
        if (catelogId != 0)
            queryWrapper.eq("catelog_id", catelogId);
        String key = (String) params.get("key");
        if (key != null && !key.isEmpty())
            queryWrapper.and(q -> q.like("attr_name", key).or().like("value_select", key));
        IPage<AttrEntity> iPage = baseDao.selectPage(getPage(params, null, false), queryWrapper);
        List<AttrEntity> records = iPage.getRecords();
//        boolean findGroup = getGroup;
        if (records.size() > 0) {
            List<AttrVo> collect = records.stream().map((entity) -> {
                AttrVo attrVo = new AttrVo();
                BeanUtil.copyProperties(entity, attrVo);
//            // 查询分类分组名字
//            if (findGroup) {
//                AttrAttrgroupRelationEntity relationEntity = relationService.selectBYAttrId(entity.getAttrId());
//                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
//                    AttrGroupEntity attrGroupEntity = attrGroupService.selectById(relationEntity.getAttrGroupId());
//                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
//                }
//            }
//            Map<String, Object> pathAndName = categoryService.findPathAndName(entity.getCatelogId());
//            List<Long> pathId = (List<Long>) pathAndName.get("pathId");
//            List<String> pathName = (List<String>) pathAndName.get("pathName");
//            if (pathId.size()>0) {
//                attrVo.setCategoryPath(pathId.toArray(new Long[pathId.size()]));
//                String categoryPathName = pathName.toString().replaceAll(", ", "/").replace("[", "").replace("]", "");
//                attrVo.setCategoryPathName(categoryPathName);
//                attrVo.setCatelogName(pathName.get(pathName.size()-1));
//            }
//            return attrVo;
                return getConcatInfo(attrVo, entity);
            }).collect(Collectors.toList());
            PageData<AttrVo> pageData = new PageData<AttrVo>(collect, iPage.getTotal());
            return pageData;
        }
        return new PageData<>(null, 0);
    }

    @Override
    public AttrVo getAllDataInfo(Long id) {
        AttrEntity attrEntity = baseDao.selectById(id);
        AttrVo attrVo = new AttrVo();
        BeanUtil.copyProperties(attrEntity, attrVo);
        return getConcatInfo(attrVo, attrEntity);
    }

    @Transactional
    @Override
    public void updateAllInfo(AttrDTO dto) {
        // 更新基本数据
        update(dto);
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(dto.getAttrId());
        relationEntity.setAttrGroupId(dto.getAttrGroupId());
        // 查询是否存在分组关系
        AttrAttrgroupRelationEntity entity = relationService.findByAttrId(dto.getAttrId());
        if (entity != null) {
            relationEntity.setId(entity.getId());
            relationService.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("id", relationEntity.getId()));
        } else {
            relationService.saveEntity(relationEntity);
        }

    }

    @Override
    public List<AttrEntity> ListByIds(List<Long> ids) {
        return baseDao.selectBatchIds(ids);
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationVos) {
        relationService.deleteBatchByParams(relationVos);
    }

    @Override
    public PageData<AttrDTO> selectWithOutInCollection(Map<String, Object> params, Long catelogId, List<Long> attrIds) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType());
        if (attrIds.size() > 0)
            queryWrapper.notIn("attr_id", attrIds);
        String key = (String) params.get("key");
        if (key != null && !key.isEmpty())
            queryWrapper.and(q -> q.like("attr_name", key).or().like("value_select", key));
        IPage<AttrEntity> selectPage = baseDao.selectPage(getPage(params, null, false), queryWrapper);
        List<AttrEntity> records = selectPage.getRecords();
        return new PageData<>(ConvertUtils.sourceToTarget(records, AttrDTO.class), selectPage.getTotal());
    }

    @Override
    public List<AttrDTO> ListAttrByCatelogIdAndAttrType(Long catelogId,int type) {
        List<AttrEntity> entityList = baseDao.selectList(new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",type));
        return ConvertUtils.sourceToTarget(entityList, AttrDTO.class);
    }

    @Override
    public List<Long> ListSearchAttrsByIds(List<Long> attrIds) {
        return baseDao.ListSearchAttrsByIds(attrIds);
    }


    /**
     * @param attrVo     前端显式的对象
     * @param attrEntity 数据存储对象
     * @return 为前端显式对象添加：category、category全路径、以及 attr 相关分组从属信息
     */
    public AttrVo getConcatInfo(AttrVo attrVo, AttrEntity attrEntity) {
        Map<String, Object> categoryPath = categoryService.findPathAndName(attrEntity.getCatelogId());
        List<Long> pathId = (List<Long>) categoryPath.get("pathId");
        List<String> pathName = (List<String>) categoryPath.get("pathName");
        if (pathId.size() > 0) {
            attrVo.setCategoryPath(pathId.toArray(new Long[pathId.size()]));
            String categoryPathName = pathName.toString().replaceAll(", ", "/").replace("[", "").replace("]", "");
            attrVo.setCategoryPathName(categoryPathName);
            attrVo.setCatelogName(pathName.get(pathName.size() - 1));
        }
        // sale 没有 属性分组相关数据
        if (attrEntity.getAttrType() != ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType()) {
            // 添加属性分组数据
            AttrAttrgroupRelationEntity relationEntity = relationService.selectBYAttrId(attrEntity.getAttrId());
            if (relationEntity!=null) {
                Long attrGroupId = relationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupService.selectById(attrGroupId);
                if (attrGroupEntity!=null) {
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    attrVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
        }
        return attrVo;
    }
}